<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="basic"
    layout="vertical"
    :hideRequiredMark="readOnly || !!$route.params.id"
  >
    <FormItem
      v-for="item in basicInfoForm"
      :key="item.key"
      :formItemConfig="item"
      :onlyRead="readOnly || !!$route.params.id"
      v-model:formState="formState[item.key || '']"
    ></FormItem>
    <a-button
      type="primary"
      v-if="!$route.params.id"
      @click="handleSubmitClick"
      >{{ $route.params.id ? "提交修改" : "提交" }}</a-button
    >
  </a-form>
</template>
<script lang="ts" setup>
import FormItem from "@/components/Form/FormItem.vue";
import { getCurrentInstance, ref } from "vue";
import { createProject, getProjectDetail } from "@/api";
import { basicInfoForm } from "./config";
import { useRoute, useRouter } from "vue-router";
// const formState = ref<Record<string, any>>({
//   rangeDates: [],
//   fileList: [],
// });
const props = defineProps<{ readOnly: boolean; routeNamePrefix: string }>();
const formState = ref<Record<string, any>>({});
const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
const formRef = ref();
const route = useRoute();
const router = useRouter();
if (route.params.id) {
  $loading?.start();
  getProjectDetail(route.params.id as string)
    .then((res) => {
      formState.value = res;
      if (res.status !== +route.params.status) {
        router.replace({
          name: route.name || "",
          params: {
            ...route.params,
            status: res.status,
          },
        });
      }
    })
    .catch(console.error)
    .finally(() => $loading?.stop());
}
const handleSubmitClick = async () => {
  try {
    $loading?.start();
    const values = await formRef.value?.validate();
    const { rangeDates, fileList, ...rest } = values;
    const [startDate, endDate] = rangeDates;
    const params = {
      startDate: startDate.valueOf(),
      endDate: endDate.valueOf(),
      fileList: fileList.map((item: any) => item.id),
      ...rest,
    };
    const id = await createProject(params);
    router.push({
      name: props.routeNamePrefix + "ProjectIndicator",
      params: Object.assign(
        {},
        route.params,
        route.params.id === "" ? { id, status: 0 } : {}
      ),
    });
  } catch (e) {
    console.error(e);
  } finally {
    $loading?.stop();
  }
};
</script>
<style lang="scss" scoped>
:deep(.ant-form-item-control-input-content > *) {
  width: 100%;
}
</style>
